package com.itheima.d12_search_binary;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 目标：掌握二分查找的实现原理和编码流程
 */
public class Test {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的数字：");
        int num = sc.nextInt();

        int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

        int  result = binarySearch(arr, num);

        System.out.println("最终结果："+ result);


        int result2 = Arrays.binarySearch(arr, num);
        System.out.println("Arrays结果："+ result2);

    }

    private static int binarySearch(int[] arr, int num) {
        //1.定义两个变量，记录左右位置
        int left = 0;
        int right = arr.length - 1;

        //2.循环查找数据：left<=right
        while(left <= right){

            //3.获取中间位置的数据
            int mid = (left + right) >>> 1; // (left + right) / 2

            //4.判断中间位置的数据的情况:arr[mid]   ?  num
            if(num ==  arr[mid]){
               return mid;
            }else if(num > arr[mid]){
                //去除左边一半无效数据
                left = mid + 1;
            }else{
                //去除右边一半无效数据
                right = mid - 1;
            }
        }
        return -1;
    }
}





